/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.jf.cloud.unicomdata.controller.admin;

import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.unicomdata.dto.EventRegDTO;
import com.jf.cloud.unicomdata.model.EventReg;
import com.jf.cloud.unicomdata.service.EventRegService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import ma.glasnost.orika.MapperFacade;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zz
 * @date 2023-05-21 08:40:16
 */
@RestController("unicomEventRegController")
@RequestMapping("/unicom/event_reg")
@Tag(name = "")
public class EventRegController {

    @Autowired
    private EventRegService eventRegService;

    @Autowired
    private MapperFacade mapperFacade;


    @GetMapping("/page")
    @Operation(summary = "获取列表", description = "分页获取列表")
    public ServerResponseEntity<PageVO<EventReg>> page(@Valid PageDTO pageDTO, @ParameterObject EventRegDTO eventRegDTO) {
        PageVO<EventReg> eventRegPage = eventRegService.page(pageDTO,eventRegDTO);
        return ServerResponseEntity.success(eventRegPage);
    }

    @GetMapping("/count/{type}")
    @Operation(summary = "统计", description = "统计")
    public ServerResponseEntity<Integer> count(@PathVariable String type) {

        return ServerResponseEntity.success(eventRegService.countByType(type));
    }

    @GetMapping("/countSex/{type}/{sex}")
    @Operation(summary = "统计", description = "统计")
    public ServerResponseEntity<Integer> countSex(@PathVariable("type") String type,@PathVariable("sex") Integer sex) {

        return ServerResponseEntity.success(eventRegService.countByTypeSex(type, sex));
    }

    @GetMapping
    @Operation(summary = "获取", description = "根据id获取")
    public ServerResponseEntity<EventReg> getById(@RequestParam Long id) {
        return ServerResponseEntity.success(eventRegService.getById(id));
    }


        /**
         * 判断给定的字符串是否是中国大陆的身份证号码
         *
         * @param idCard 身份证号码
         * @return 如果是合法的身份证号码返回true，否则返回false
         */
        public static boolean isValidIdCard(String idCard) {
            if (idCard == null || idCard.length() != 18) {
                return false;
            }

            // 检查前17位是否都是数字
            for (int i = 0; i < 17; i++) {
                if (!Character.isDigit(idCard.charAt(i))) {
                    return false;
                }
            }

            // 检查第18位是否是数字或X
            char lastChar = idCard.charAt(17);
            if (!(Character.isDigit(lastChar) || lastChar == 'X')) {
                return false;
            }

            // 这里可以添加更复杂的校验逻辑，例如加权求和校验
            // 但是为了简化，我们只做基本的格式检查

            return true;
        }




    @PostMapping
    @Operation(summary = "保存", description = "保存")
    public ServerResponseEntity<Void> save(@Valid @RequestBody EventRegDTO eventRegDTO) {
        EventReg eventReg = mapperFacade.map(eventRegDTO, EventReg.class);
        eventReg.setId(null);
        eventReg.setCardNo(eventReg.getCardNo().trim());
        eventReg.setPhone(eventReg.getPhone().trim());
        if(RedisUtil.hasKey("user_"+eventReg.getClothingSize()+"-"+eventReg.getPhone())){
            return ServerResponseEntity.showFailMsg("不能重复报名");
        }
        if(RedisUtil.hasKey("user_"+eventReg.getClothingSize()+"-"+eventReg.getCardNo())){
            return ServerResponseEntity.showFailMsg("不能重复报名");
        }
        if("100".equals(eventReg.getClothingSize()) || "101".equals(eventReg.getClothingSize())){
            if(eventReg.getCardNo().length()!=18){
                return ServerResponseEntity.showFailMsg("身份证长度有误");
            }
            //判断身份证和手机号是否符合各自规则
            if(!isValidIdCard(eventReg.getCardNo())){
                return ServerResponseEntity.showFailMsg("身份证有误");
            }
            if(!eventReg.getPhone().matches("^1[3456789]\\d{9}$")){
                return ServerResponseEntity.showFailMsg("手机号有误");
            }
            if(eventReg.getPhone().length()!=11){
                return ServerResponseEntity.showFailMsg("手机号长度有误");
            }
        }
        if("102".equals(eventReg.getClothingSize())){
            if(eventReg.getPhone().length()!=11){
                return ServerResponseEntity.showFailMsg("手机号长度有误");
            }
            if(!eventReg.getPhone().matches("^1[3456789]\\d{9}$")){
                return ServerResponseEntity.showFailMsg("手机号有误");
            }
            if(eventReg.getCardNo().length()!=8 && eventReg.getCardNo().length()!=7){
                return ServerResponseEntity.showFailMsg("车牌号有误");
            }
            //判断前2位是否为湘M
            if(eventReg.getCardNo().substring(0,2).equals("湘M")){
                return ServerResponseEntity.showFailMsg("本地车牌不能参与");
            }
        }

            long nowtime = System.currentTimeMillis();
            String endTime = eventRegService.getEndTime(eventReg.getClothingSize());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            try {
                if(nowtime > sdf.parse(endTime).getTime()){
                    return ServerResponseEntity.showFailMsg("已过时间");
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
//        }
        Date createTime = new Date();
        eventReg.setCreateTime(createTime);

        eventRegService.save(eventReg);
        RedisUtil.set("user_"+eventReg.getClothingSize()+"-"+eventReg.getPhone(),"1",86400);
        RedisUtil.set("user_"+eventReg.getClothingSize()+"-"+eventReg.getCardNo(),"1",86400);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新", description = "更新")
    public ServerResponseEntity<Void> update(@Valid @RequestBody EventRegDTO eventRegDTO) {
        EventReg eventReg = mapperFacade.map(eventRegDTO, EventReg.class);
        eventRegService.update(eventReg);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除", description = "根据id删除")
    public ServerResponseEntity<Void> delete(@RequestParam Long id) {
        eventRegService.deleteById(id);
        return ServerResponseEntity.success();
    }
}
